package com.wuyanzu.shixicoderedo.controller;

import com.wuyanzu.shixicoderedo.common.dto.MessageQueryDTO;
import com.wuyanzu.shixicoderedo.service.MessageService;
import com.wuyanzu.shixicoderedo.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/messages")
@Slf4j
public class MessageController {


    @Autowired
    private TokenService tokenService;
    @Autowired
    private MessageService messageService;

    /**
     * 获取消息列表
     * @param dto
     * @param req
     */
    @PostMapping("/list")
    public Map<String,Object> list(@RequestBody MessageQueryDTO dto, HttpServletRequest req) {
        String token = req.getHeader("Authorization");
        // log.info("token: " + token);
        String userIdStr = tokenService.getUserIdFromToken(token);
        if (userIdStr == null) {
            throw new RuntimeException("unauthorized");
        }
        dto.setUserId(Long.parseLong(userIdStr));
        return messageService.queryMessages(dto);
    }

    /**
     * 页面进入时拉取最近未读消息（只接受 limit）
     * Body 示例： { "limit": 10 }
     */
    @PostMapping("/unread/recent")
    public Map<String, Object> recentUnread(@RequestBody(required = false) Map<String, Object> body,
                                            HttpServletRequest req) {
        String token = req.getHeader("Authorization");
        // log.info("token: " + token);
        String userIdStr = tokenService.getUserIdFromToken(token);
        if (userIdStr == null) {
            throw new RuntimeException("unauthorized");
        }
        Long userId = Long.parseLong(userIdStr);

        int limit = 10;
        if (body != null && body.get("limit") != null) {
            try {
                limit = Integer.parseInt(String.valueOf(body.get("limit")));
            } catch (NumberFormatException ignored) {
            }
        }
        if (limit <= 0) limit = 10;
        if (limit > 100) limit = 100; // 上限保护

        return messageService.getRecentUnread(userId, limit);
    }


}
